package cn.bupt.adt.controller.inf;

import cn.bupt.adt.entity.autogenerate.CheckInstiAppUser;
import cn.bupt.adt.entity.autogenerate.CheckInstiView;
import cn.bupt.adt.entity.autogenerate.InspectOrder;
import cn.bupt.adt.entity.autogenerate.InspectOrderView;
import cn.bupt.adt.model.CheckInstitutionModel;
import cn.bupt.adt.service.ICheckInstiAppUserService;
import cn.bupt.adt.service.IInstitutionService;
import cn.bupt.adt.service.IinspectOrderService;
import cn.bupt.adt.service.impl.CheckInstitutionService;
import cn.bupt.adt.util.MD5Util;
import cn.bupt.adt.util.NetDataAccessUtil;
import cn.bupt.adt.util.RedisUtil;
import cn.bupt.adt.util.UserUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/publicApp/inspetion")
public class InspectionController {

    @Autowired
    ICheckInstiAppUserService checkInstiAppUserService;

    @Autowired
    IinspectOrderService inspectOrderService;

    @Autowired
    CheckInstitutionService checkInstitutionService;

    @Autowired
    IInstitutionService institutionService;

    @RequestMapping("/login")
    @ResponseBody
    //注册需要填写账号account，密码passwd
    public Object login(CheckInstiAppUser user, HttpServletRequest request) {
//		response.setHeader("Access-Control-Allow-Origin", "*");
        NetDataAccessUtil nau = new NetDataAccessUtil();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if ("GET".equals(request.getMethod()) || null == user) {
            nau.setContent(null);
            nau.setResult(-3);
            nau.setResultDesp("请求错误！");
        } else {
            CheckInstiView ins = checkInstiAppUserService.getInsByAccount(user.getAccount());
            if (ins == null) {
                //用户未注册
                nau.setContent(null);
                nau.setResult(-1);
                nau.setResultDesp("该用户不存在！");

            } else {
                if (!ins.getPasswd().equals(MD5Util.MD5(user.getPasswd()))) {
                    //密码不正确
                    nau.setContent(null);
                    nau.setResult(-2);
                    nau.setResultDesp("密码错误！");
                } else {
                    //登录成功，清除之前的token信息
                    Jedis redis = RedisUtil.getJedis();
                    Date loginTime = new Date();
                    String key = UserUtil.generateToken(user.getAccount(), df.format(loginTime));
                    if (redis.exists(key)) {
                        redis.del(key);
                        RedisUtil.returnResource(redis);
                    }
                    checkInstiAppUserService.updateLoginTimeById(ins.getId(), loginTime);
                    //生成token,存token到redis
                    String token = UserUtil.generateToken(user.getAccount(), df.format(loginTime));
                    RedisUtil.set(token, ins.getId());
                    //返回信息
                    nau.setContent(UserUtil.constructCheckInsUserResp(ins, token));
                    nau.setResult(1);
                    nau.setResultDesp("登录成功");
                }
            }
        }
        return nau;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Object logout(HttpServletRequest request) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        Integer userId = (Integer) request.getAttribute("userId");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CheckInstiAppUser ins = checkInstiAppUserService.getInsById(userId);
        String key = MD5Util.MD5(ins.getAccount() + df.format(ins.getLastLoginTime()));
        if (RedisUtil.exist(key)) {
            RedisUtil.del(key);
            nau.setContent(null);
            nau.setResult(1);
            nau.setResultDesp("登出成功！");
        } else {
            nau.setResult(0);
            nau.setResultDesp("登出失败！");
        }
        return nau;
    }

    @RequestMapping(value = "/changePasswd", method = RequestMethod.POST)
    @ResponseBody
    //修改密码需要传入token，旧密码passwd,新密码newPasswd
    public Object changePasswd(HttpServletRequest request, String passwd, String newPasswd) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        Integer userId = (Integer) request.getAttribute("userId");
        CheckInstiAppUser ins = checkInstiAppUserService.getInsById(userId);
        if (!MD5Util.MD5(passwd).equals(ins.getPasswd())) {
            //输入原密码不对
            nau.setContent(null);
            nau.setResult(0);
            nau.setResultDesp("输入旧密码不正确，请确认您的旧密码");
        } else {
            if (checkInstiAppUserService.changePasswd(ins, newPasswd)) {
                RedisUtil.del(request.getParameter("token"));
                nau.setContent(null);
                nau.setResult(1);
                nau.setResultDesp("修改密码成功,请重新登录");
            } else {
                nau.setContent(null);
                nau.setResult(0);
                nau.setResultDesp("因网络或其他原因，修改密码失败，请稍后尝试");
            }
        }
        return nau;
    }

    @RequestMapping(value = "/getCheckInstiInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object getInstitutionInfo(HttpServletRequest request) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        Integer userId = (Integer) request.getAttribute("userId");
        CheckInstiView ins = checkInstiAppUserService.getInsViewById(userId);
        if (ins != null) {
            nau.setContent(UserUtil.constructCheckInsUserResp(ins, request.getParameter("token")));
            nau.setResult(1);
            nau.setResultDesp("获取检查机构信息成功");
        } else {
            nau.setContent(null);
            nau.setResult(0);
            nau.setResultDesp("获取检查机构信息失败");

        }
        return nau;
    }

    //获取已接单检查项目订单列表
    @RequestMapping("/getTakedInspectItemsOrders")
    @ResponseBody
    public Object getTakedInspectItems(HttpServletRequest request, Integer pageSize, Integer pageNum) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        Page<?> page = PageHelper.startPage(pageNum, pageSize, "id desc");
        List<InspectOrderView> inspectOrderView = inspectOrderService.getAllInspectItemOrders();
        if (inspectOrderView.size() != 0) {
            Map<String, Object> content = new HashMap<>();
            content.put("orders", inspectOrderView);
            content.put("currentPage", page.getPageNum());
            content.put("allPages", page.getPages());
            nau.setContent(content);
//				nau.setContent(inspectOrderView);
            nau.setResult(1);
            nau.setResultDesp("获取检查项目订单列表成功");
        } else {
            nau.setContent(null);
            nau.setResult(0);
            nau.setResultDesp("获取检查项目订单列表失败");
        }
        return nau;
    }

    //获取检查项目所有订单列表
    @RequestMapping("/getInspectItemsOrders")
    @ResponseBody
    public Object getInspectItems(HttpServletRequest request, Integer pageSize, Integer pageNum) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        Page<?> page = PageHelper.startPage(pageNum, pageSize, "id desc");
        List<InspectOrder> inspectOrder = inspectOrderService.getAllInspectItemOrdersInInspectOrder();
//			String institutionName  = institutionService.getInstitutionNameById();
        if (inspectOrder.size() != 0) {
            Map<String, Object> content = new HashMap<>();
            content.put("orders", inspectOrder);
            content.put("currentPage", page.getPageNum());
            content.put("allPages", page.getPages());
            nau.setContent(content);
//				nau.setContent(inspectOrder);
            nau.setResult(1);
            nau.setResultDesp("获取已接单检查项目订单列表成功");
        } else {
            nau.setContent(null);
            nau.setResult(0);
            nau.setResultDesp("获取已接单检查项目订单列表失败");
        }
        return nau;
    }

    //检查机构修改订单状态
    //更改订单状态,变1为接单、变2为取回样品、变3为检验完成
    @RequestMapping("/takeOrder")
    @ResponseBody
    public Object takeOrder(HttpServletRequest request, InspectOrder order) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        Integer userId = (Integer) request.getAttribute("userId");
        CheckInstitutionModel ins = checkInstitutionService.getInstitutionById(userId);
        boolean rst = inspectOrderService.takeOrder(order, userId);
        if (rst) {
            nau.setResult(1);
            nau.setResultDesp("接单成功");
        } else {
            nau.setResult(0);
            nau.setResultDesp("接单失败");
        }
        return nau;
    }

    @RequestMapping("/changeOrderStatus")
    @ResponseBody
    public Object changeOrderStatus(HttpServletRequest request, InspectOrderView order) {
        boolean rst = inspectOrderService.updateOrder(order);
        NetDataAccessUtil nau = new NetDataAccessUtil();
        if (rst) {
            nau.setResult(1);
            nau.setResultDesp("修改检查项目订单状态成功");
        } else {
            nau.setResult(0);
            nau.setResultDesp("修改检查项目订单状态失败");
        }
        return nau;
    }

    @RequestMapping("/findOrderById")
    @ResponseBody
    public Object findOrderById(HttpServletRequest request, int id) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        InspectOrder inspectOrder = inspectOrderService.getOrderById(id);
        if (inspectOrder != null) {
            nau.setContent(inspectOrder);
            nau.setResult(1);
            nau.setResultDesp("搜索检查项目订单成功");
        } else {
            nau.setContent(null);
            nau.setResult(0);
            nau.setResultDesp("该订单不存在");
        }
        return nau;
    }
}
